package com.xdf.docmanagementsystem.service.impl;

import com.xdf.docmanagementsystem.dao.DepartmentMapper;
import com.xdf.docmanagementsystem.dao.EmployeeMapper;
import com.xdf.docmanagementsystem.entity.Department;
import com.xdf.docmanagementsystem.entity.Employee;
import com.xdf.docmanagementsystem.service.ValidateService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @program: doc-management-system
 * @description:部门验证
 * @author: Zhang
 * @create: 2020-06-30 10:22
 **/
@Service
public class DepartmentValidateServiceImpl implements ValidateService<Department> {

    private DepartmentMapper departmentMapper;
    private EmployeeMapper employeeMapper;

    @Autowired
    public DepartmentValidateServiceImpl(DepartmentMapper departmentMapper, EmployeeMapper employeeMapper) {
        this.departmentMapper = departmentMapper;
        this.employeeMapper = employeeMapper;
    }

    @Override
    public boolean shouldInsert(Department item) throws Exception {
        if (item == null || StringUtils.isEmpty(item.getDepartmentName())) return false;
        List<Department> list = departmentMapper.selectByParam(Department.builder().departmentName(item.getDepartmentName()).detartmentStatus(1).build());
        return list == null || list.size() <= 0;
    }

    @Override
    public boolean shouldUpdate(Department item) throws Exception {
        if (item == null || item.getId() == null) {
            return false;
        }
        List<Department> list = departmentMapper.selectByParam(Department.builder().departmentName(item.getDepartmentName()).detartmentStatus(1).build());
        if (CollectionUtils.isEmpty(list)) return true;
        if (list.size() == 1) {
            Department department = list.get(0);
            return Objects.equals(department.getId(), item.getId());
        }
        return false;
    }

    @Override
    public boolean shouldDelete(Department item) throws Exception {
        if (item == null || item.getId() == null) {
            return false;
        }
        List<Department> children = departmentMapper.selectByParam(Department.builder().departmentParentId(item.getId()).detartmentStatus(1).build());
        List<Employee> employees = employeeMapper.selectByParam(Employee.builder().docStatus(1).departmentId(item.getId()).build());
        return CollectionUtils.isEmpty(children) && CollectionUtils.isEmpty(employees);
    }
}
